from django.db import models
from django.contrib.admin import site 
from django.conf import settings
# Create your models here.

class System():
	def __init__(self):
		self.apps = {}
		self.mod = []
		
	def reg_app(self,name,visible=True):
		if name not in self.apps.keys():
			app = Module(name,visible)
			self.apps[name] = app
			self.mod.append(app)
		else:
			app = self.apps[name]
		return app


class Module():
	def __init__(self,name,visible=True,query=False):
		self.name =name
		self.visible = visible
		self.items = []
		self.query = query
		
	def reg_item(self,model,admin=None,visible=True,query=False):
		self.model = model
		item = Item(model,visible,query)
		item.do_url("/"+settings.PROJECT_NAME +"/admin/"+self.name.lower()+"/")
		self.items.append(item)
		try:
			if issubclass(model, models.Model):
				a = Action(model,'delete')
				item.actions['delete'] = a
				a = Action(model,'history')
				item.actions['history'] = a
			if admin:
				site.register(model, admin)
			else:
				site.register(model)
			try:	
				acts= site._registry[self.model].actions
				for name in acts.keys():
					a = Action(self.model, name, acts[name])
					item.actions[name] = a
			except:
				pass
		except:
				pass
class Item():
	def __init__(self,model,visible,query=False):
		self.model = model
		
		self.name = self.model.__name__.lower()
		self.visible = visible
		self.query = query
		self.actions = {}
		
	def do_url(self,url):
		self.complete_url = url + self.name +"/"

class Action():
	def __init__(self,parent, name,func=None):
		self.name = name
		self.func = func
		self.parent = parent

	def view(self, request, id):
		admin_obj = site._registry[self.parent]
		if self.name=='history':
			return admin_obj.history_view(request, id)
		elif self.name=='delete':
			return admin_obj.delete_view(request, id)
		return self.func(request, id)
	

		
system = System()

def model__action(request, app_label, model_name, id, action):
	app = system.apps[app_label]
	
	model = [i for i in app.items if i.name == model_name][0]
	action = model.actions[action]
	
	return action.view(request, id)


